% inputs:
% pooledData is the table of identifiers, etc
% numRepeats is how many bootstrap distributions to generate
% IDcolumns specifies which columnds to use as the identifiers for the
% heirarchical bootstrap
%
% identical in principle to nestedBootstrapNVCsample_v2_0, but a 3 level
% heirarcy instead of 2; really set up for use in the high res widefield
% analysis



function idx = nestedBootstrapNVCsample_3level_v2_0(pooledData,numRepeats,IDcolumns)

if nargin < 2 || isempty(numRepeats)
    numRepeats = 10000;
end

[uniqueMice,~,mouseID] = unique(pooledData(:,IDcolumns(1)));
nummice = size(uniqueMice,1);
mice = cell(1,nummice);
for n = 1:length(mice)
    %find unique mice
    i1 = mouseID == n;
    temp = pooledData(i1,:);
    [uid,~,ic] = unique(temp(:,IDcolumns(2)));
    
    mice{n} = cell(1,size(uid,1));
    for n2 = 1:size(uid,1)
        i2 = ic == n2;
        [uid2,~,ic2] = unique(temp(i2,IDcolumns(3)));
        mice{n}{n2} = cell(2,size(uid2,1));
        for n3 = 1:size(uid2,1)
            mice{n}{n2}{1,n3} = uid2{n3,1};            %stores the identity of the repeat
            mice{n}{n2}{2,n3} = find(pooledData{:,IDcolumns(3)} == uid2{n3,1});
        end
    end
end

idx = [];
for n = 1:numRepeats
    i1 = randi(nummice,nummice,1);
    mouseidx = [];
    for n2 = 1:length(i1)
        vessidx = [];
        numvessel = size(mice{i1(n2)},2);
        i2 = randi(numvessel,numvessel,1);
        for n3 = 1:length(i2)
            curidx = [];
            numseg = size(mice{i1(n2)}{i2(n3)},2);
            i3 = randi(numseg,numseg,1);
            for n4 = 1:length(i3)
                numsamples = size(mice{i1(n2)}{i2(n3)}{2,i3(n4)},1);
                i4 = randi(numsamples,numsamples,1);
                temp = mice{i1(n2)}{i2(n3)}{2,i3(n4)};
                curidx = [curidx;temp(i4)];
            end
            vessidx = nancat_v2(vessidx,curidx,2);
        end
        mouseidx = nancat_v2(mouseidx,vessidx,3);
    end
    idx = nancat_v2(idx,mouseidx,4);
end

